<?php
declare(strict_types=1);

namespace app\shop\logic;

use app\shop\exception\ParamsErrorException;
use app\shop\model\goods\GoodsModel;
use app\shop\model\user\UserFavoriteModel;
use think\helper\Arr;
use think\Paginator;

class UserFavoriteLogic extends BaseLogic
{
    /**
     * 列表
     * @param array $params
     * @return array|Paginator
     */
    public function list(array $params): Paginator|array
    {
        $query = UserFavoriteModel::getQuery();

        $query->with(['goods']);

        $query->where('user_id', $params['user_id']);

        return UserFavoriteModel::paginateListQuery($query);
    }

    /**
     * 添加
     * @param $params
     * @return bool
     * @throws ParamsErrorException
     */
    public function add($params): bool
    {
        $goods = GoodsModel::where('id', $params['goods_id'])->findOrEmpty();
        if ($goods->isEmpty()) {
            throw new ParamsErrorException('商品已下架');
        }
        $favorite = UserFavoriteModel::where([
            ['user_id', '=', $params['user_id']],
            ['goods_id', '=', $params['goods_id']]
        ])->withTrashed()->findOrEmpty();
        if ($favorite->isEmpty()) {
            $favorite = UserFavoriteModel::create([
                'user_id'   => $params['user_id'],
                'goods_id'  => $params['goods_id'],
                'old_price' => $goods->min_price,
            ]);
            $result   = $favorite->id > 0;
        } else {
            $result              = $favorite->restore();
            $favorite->old_price = $goods->min_price;
            $favorite->save();
        }

        return $result;
    }

    /**
     * 删除
     * @param array $params
     * @return bool
     */
    public function delete(array $params): bool
    {
        $where = [
            ['user_id', '=', $params['user_id']]
        ];

        if (!Arr::get($params, 'is_all')) {
            $where[] = ['goods_id', '=', $params['goods_id']];
        }

        return UserFavoriteModel::destroy(function ($query) use ($where) {
            $query->where($where);
        });
    }
}